/**
 * Created by liuqingxia on 2016/3/24.
 */

var currentGroupRuleId;
var currentGroupId;

/**
 * 获取GroupRuleVO数组
 * @param appId
 * @returns {Array}
 */
function getGroupRuleVOByAppId(appId) {
    var groupRuleVOs = [];
    $.postHttpSync({appId: appId}, getUrlBySuffix("/tddl/groupRuleVO/findByAppId"), function (json) {
        if (json && json.success) {
            groupRuleVOs = json['list'];
        }
    })
    return groupRuleVOs;
}

/**
 * 把GroupRuleVO数组，按照groupName,
 * 分成小的GroupRuleVO数组
 * @param groupRuleVOs
 */
function getSplitGroupRuleVOs(groupRuleVOs) {
    var allSplitGroupRuleVOs = [];

    var singleSplitGroupRuleVOs = [];

    var currGroupName = "";

    for (var index in groupRuleVOs) {

        var groupRuleVO = groupRuleVOs[index];

        if (0 == index) {
            currGroupName = groupRuleVO['groupName'];
            singleSplitGroupRuleVOs.push(groupRuleVO);
            if (1 == groupRuleVOs.length) {
                allSplitGroupRuleVOs.push(singleSplitGroupRuleVOs);
                break;
            }
            continue;
        }

        if (groupRuleVO['groupName'] == currGroupName) {

            singleSplitGroupRuleVOs.push(groupRuleVO);

            if (index == groupRuleVOs.length - 1) {
                allSplitGroupRuleVOs.push(singleSplitGroupRuleVOs);
                break;
            }


        } else {

            allSplitGroupRuleVOs.push(singleSplitGroupRuleVOs);
            singleSplitGroupRuleVOs = [];
            singleSplitGroupRuleVOs.push(groupRuleVO);

            if (index == groupRuleVOs.length - 1) {
                allSplitGroupRuleVOs.push(singleSplitGroupRuleVOs);
                break;
            }

            currGroupName = groupRuleVO['groupName'];
        }

    }

    return allSplitGroupRuleVOs;
}

/**
 * 生成GroupRuleVO表格
 * @param splitGroupRuleVOs
 * @returns {string}
 */
function generateGroupRuleVOTable(splitGroupRuleVOs) {

    var trs = "";

    for (var index in splitGroupRuleVOs) {

        var singleGroupRuleVOs = splitGroupRuleVOs[index];
        var evenOrOdd = "even";

        if (index % 2 == 0) {
            evenOrOdd = "odd";
        }

        trs += generateGroupRuleVOTRs(singleGroupRuleVOs, evenOrOdd);

    }

    var table = "" +
        " <table " +
        "class='table table-stripped toggle-arrow-tiny " +
        "footable no-paging footable-loaded' data-page-size='10' " +
        "style='font-size: 14px'>" +
        "<thead>" +
        "<th  style='text-align:center;display: none'>id</th>" +
        "<th  style='text-align:center;display: none'>groupId</th>" +
        "<th  style='text-align:center;'>groupName</th>" +
        "<th class='footable-sortable'>数据源</th>" +
        "<th class='footable-sortable'>写权重</th>" +
        "<th class='footable-sortable'>写优先级</th>" +
        "<th class='footable-sortable'>读权重</th>" +
        "<th class='footable-sortable'>读优先级</th>" +
        "<th class='footable-sortable'>是否备库</th>" +
        "<th class='footable-sortable'>数据库状态</th>" +
        "<th class='footable-sortable'>操作</th>" +
        "</thead>" +
        "<tbody>" + trs + "</tbody>" +
        "</table>";

    return table;

}

/**
 * 返回GroupRuleVO的<tr>标签
 * @param singleGroupRuleVOs
 * @returns {string}
 */
function generateGroupRuleVOTRs(singleGroupRuleVOs, evenOrOdd) {

    var trs = "";
    var rows = singleGroupRuleVOs.length;

    for (var index in singleGroupRuleVOs) {

        var groupRuleVO = singleGroupRuleVOs[index];

        var rowspan = "";

        if (index == 0) {
            rowspan = "<td align='center' style='display:table-cell; vertical-align:middle' rowspan='" + rows + "'>" + groupRuleVO['groupName'] + "</td>";
        }

        trs += "<tr class='footable-" + evenOrOdd + "' style='display: table-row;'>" +
        "<td class='id-td' style='display: none'>" +
        "<span class='id-span'>" +
        groupRuleVO['id'] +
        "</span>" +
        "</td>" +
        "<td class='groupId-tr' style='display: none'>" +
        "<span class='id-span'>" +
        groupRuleVO['groupId'] +
        "</span>" +
        "</td>" +
        rowspan +
        "<td class='groupRuleInfo'>" + groupRuleVO['groupRuleName'] + "<input name='groupRuleId' value='"+groupRuleVO['id']+"' type='hidden' /><input name='groupName' value='"+groupRuleVO['groupName']+"' type='hidden' /></td>" +
        "<td class='writeWeight' style='width:12%;'><span class='writeWeightSpan'>" + groupRuleVO['writeWeight'] + "</span><span class='writeWeightInput' style='display:none;'><input type='number' value='"+groupRuleVO['writeWeight']+"' name='writeWeight' min='0' style='width:25%;' /></span></td>" +
        "<td class='writePriority' style='width:12%;'><span class='writePrioritySpan'>" + groupRuleVO['writePriority'] + "</span><span class='writePriorityInput' style='display:none;'><input type='number' value='"+groupRuleVO['writePriority']+"' name='writePriority' min='0' style='width:25%;' /></span></td>" +
        "<td class='readWeight' style='width:12%;'><span class='readWeightSpan'>" + groupRuleVO['readWeight'] + "</span><span class='readWeightInput' style='display:none;'><input type='number' value='"+groupRuleVO['readWeight']+"' name='readWeight' min='0' style='width:25%;' /></span></td>" +
        "<td class='readPriority' style='width:12%;'><span class='readPrioritySpan'>" + groupRuleVO['readPriority'] + "</span><span class='readPriorityInput' style='display:none;'><input type='number' value='"+groupRuleVO['readPriority']+"' name='readPriority' min='0' style='width:25%;' /></span></td>" +
        "<td>" + isBak(groupRuleVO['isBak']) + "</td>" +
        "<td>" + dataSourceStatus(groupRuleVO['dataSourceStatus']) + "</td>" +
        "<td><button class='btn btn-updateDiamondInfo' type='button' name='updateDiamondInfo'>修改</button></td>" +
        "</tr>";

    }
    updateDiamondInfo();
    saveDiamondInfo();
    return trs;
}


function updateDiamondInfo(){
	$(document).on("click",".btn-updateDiamondInfo",function(){
		var thisObj=$(this);
		buttonEvent(thisObj);
	})
}
function buttonEvent(thisObj){
	if($(thisObj).hasClass("btn-updateDiamondInfo")){
		$(thisObj).addClass("btn-saveDiamondInfo");
		$(thisObj).html("保存");
		$(thisObj).removeClass("btn-updateDiamondInfo");
		$(thisObj).parent("td").siblings(".writeWeight").find(".writeWeightSpan").hide();
		$(thisObj).parent("td").siblings(".writeWeight").find(".writeWeightInput").show();
		$(thisObj).parent("td").siblings(".writePriority").find(".writePrioritySpan").hide();
		$(thisObj).parent("td").siblings(".writePriority").find(".writePriorityInput").show();
		$(thisObj).parent("td").siblings(".readWeight").find(".readWeightSpan").hide();
		$(thisObj).parent("td").siblings(".readWeight").find(".readWeightInput").show();
		$(thisObj).parent("td").siblings(".readPriority").find(".readPrioritySpan").hide();
		$(thisObj).parent("td").siblings(".readPriority").find(".readPriorityInput").show();
	}else{
		$(thisObj).addClass("btn-updateDiamondInfo");
		$(thisObj).html("修改");
		$(thisObj).removeClass("btn-saveDiamondInfo");
		$(thisObj).parent("td").siblings(".writeWeight").find(".writeWeightSpan").html($(thisObj).parent("td").siblings(".writeWeight").find("input[name=writeWeight]").val());
		$(thisObj).parent("td").siblings(".writeWeight").find(".writeWeightSpan").show();
		$(thisObj).parent("td").siblings(".writeWeight").find(".writeWeightInput").hide();
		$(thisObj).parent("td").siblings(".writePriority").find(".writePrioritySpan").html($(thisObj).parent("td").siblings(".writePriority").find("input[name=writePriority]").val());
		$(thisObj).parent("td").siblings(".writePriority").find(".writePrioritySpan").show();
		$(thisObj).parent("td").siblings(".writePriority").find(".writePriorityInput").hide();
		$(thisObj).parent("td").siblings(".readWeight").find(".readWeightSpan").html($(thisObj).parent("td").siblings(".readWeight").find("input[name=readWeight]").val());
		$(thisObj).parent("td").siblings(".readWeight").find(".readWeightSpan").show();
		$(thisObj).parent("td").siblings(".readWeight").find(".readWeightInput").hide();
		$(thisObj).parent("td").siblings(".readPriority").find(".readPrioritySpan").html($(thisObj).parent("td").siblings(".readPriority").find("input[name=readPriority]").val());
		$(thisObj).parent("td").siblings(".readPriority").find(".readPrioritySpan").show();
		$(thisObj).parent("td").siblings(".readPriority").find(".readPriorityInput").hide();
	}
	
}
function saveDiamondInfo(){
	$(document).on("click",".btn-saveDiamondInfo",function(){
		var thisObj = $(this);
		var params = getParams(thisObj);
		var url=getUrlBySuffix("/tddl/grop/updateGroupRuleInfo");
		$.post(url,params,function(json){
			if(json&& json.success){
				swal("成功","成功","success");
				buttonEvent(thisObj);
			}else{
				swal("提示","失败","info");
			}
		})
	})
}
function getParams(thisObj){
	var param={}
	param.groupName=$(thisObj).parent("td").siblings(".groupRuleInfo").find("input[name=groupName]").val();
	param.id=Number($(thisObj).parent("td").siblings(".groupRuleInfo").find("input[name=groupRuleId]").val());
	param.writeWeight=Number($(thisObj).parent("td").siblings(".writeWeight").find("input[name=writeWeight]").val());
	param.writePriority=Number($(thisObj).parent("td").siblings(".writePriority").find("input[name=writePriority]").val());
	param.readWeight=Number($(thisObj).parent("td").siblings(".readWeight").find("input[name=readWeight]").val());
	param.readPriority=Number($(thisObj).parent("td").siblings(".readPriority").find("input[name=readPriority]").val());
	return param;
}

/**
 * 是否是备库
 * @param isBak
 * @returns {string}
 */
function isBak(isBak) {
    if (0 == isBak) {
        return "否";
    }
    return "" +
        "<span style='color: red'>" +
        "是&nbsp;&nbsp;&nbsp;&nbsp;" +
        '<a href="javascript:;" class="switchBackup-Btn">' +
        '<span class="label label-danger">' +
        '切&nbsp;换' +
        '</span>' +
        '</a>&nbsp;' +
        "</span>";
}

/**
 * 点击"切换"按钮
 */
function clickSwitchBackupBtn() {
    $(document).on("click", ".switchBackup-Btn", function (e) {
        currentGroupRuleId = getGroupRuleId($(this));//groupRuleId
        currentGroupId = getGroupId($(this));//groupId
        showSwitchBackupTip(e);
    });
}

/**
 * 显示主备切提示框
 */
function showSwitchBackupTip(e) {
    adjustTipModalPos(getMouseY(e));
    $("#switchBackup-tip-modal").modal("show");
}

/**
 * 点击"确认删除"按钮
 */
function clickConfirmSwitchBackupBtn() {
    $(document).on("click", "#confirm-SwitchBackup-btn", function () {
        var params = {};
        params['groupId'] = currentGroupId;
        params['groupRuleId'] = currentGroupRuleId;
        console.log("切换主备数据库，groupId:" + currentGroupId + ",groupRuleId:" + currentGroupRuleId);
        $.postHttpSync(params, getUrlBySuffix("/tddl/groupRule/switchBackUpDb"), function (json) {
            if (json && json.success) {
                $("#cancel-switchBackup-btn").trigger("click");
                swal("成功", json.message, "success");
                return;
            } else {
                $("#cancel-switchBackup-btn").trigger("click");
                swal("失败", json.message, "error");
                return;
            }
        })
    });
}

/**
 * 调整主备切提示框的位置
 * @param x
 */
function adjustTipModalPos(y) {
    //console.log("调整主备切提示框位置，x：" + x, "y: " + y);
    var modalEle = $('#switchBackup-tip-modal');
    var containerWidth = $("#page-wrapper").width();
    var modalWidth = modalEle.find(".modal-dialog").width() + 500;
    var x = (containerWidth - modalWidth) / 2;
    y = y - 200;
    modalEle.css({'left': x + 'px', 'top': y + 'px'});
}

/**
 * 获取groupRuleId
 * @param ele
 * @returns {*}
 */
function getGroupRuleId(ele) {
    var id = ele.parent().parent().parent().find(".id-td").find(".id-span").html()
    return $.trim(id);
}

/**
 * 获取groupId
 * @param e
 */
function getGroupId(ele) {
    var id = ele.parent().parent().parent().find(".groupId-tr").find(".id-span").html();
    return $.trim(id);
}

/**
 * 数据库是否可用
 * @param dataSourceStatus
 * @returns {string}
 */
function dataSourceStatus(dataSourceStatus) {
    if ("可用" == dataSourceStatus) {
        return "<span style='color: green'>可用</span>";
    } else {
        return "<span style='color: red'>不可用</span>";
    }
}